package com.example.munidingwei.ui.components

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp

@Composable
fun SystemMockDialog(
    onDismiss: () -> Unit,
    onEnableSystemMock: () -> Unit,
    onSetSystemMock: (latitude: Double, longitude: Double, accuracy: Float) -> Unit,
    systemMockStatus: String,
    hasMockPermission: Boolean,
    isSystemMockEnabled: Boolean,
    modifier: Modifier = Modifier
) {
    var latitude by remember { mutableStateOf("") }
    var longitude by remember { mutableStateOf("") }
    var accuracy by remember { mutableStateOf("5.0") }
    var latitudeError by remember { mutableStateOf("") }
    var longitudeError by remember { mutableStateOf("") }
    var accuracyError by remember { mutableStateOf("") }
    
    fun validateInputs(): Boolean {
        var isValid = true
        
        // 验证纬度
        latitudeError = ""
        try {
            val lat = latitude.toDouble()
            if (lat < -90 || lat > 90) {
                latitudeError = "纬度必须在-90到90之间"
                isValid = false
            }
        } catch (e: NumberFormatException) {
            latitudeError = "请输入有效的纬度"
            isValid = false
        }
        
        // 验证经度
        longitudeError = ""
        try {
            val lng = longitude.toDouble()
            if (lng < -180 || lng > 180) {
                longitudeError = "经度必须在-180到180之间"
                isValid = false
            }
        } catch (e: NumberFormatException) {
            longitudeError = "请输入有效的经度"
            isValid = false
        }
        
        // 验证精度
        accuracyError = ""
        try {
            val acc = accuracy.toFloat()
            if (acc < 0 || acc > 1000) {
                accuracyError = "精度必须在0到1000之间"
                isValid = false
            }
        } catch (e: NumberFormatException) {
            accuracyError = "请输入有效的精度"
            isValid = false
        }
        
        return isValid
    }
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    Icons.Default.Settings,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.primary
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = "系统级位置模拟",
                    fontWeight = FontWeight.Bold
                )
            }
        },
        text = {
            Column(
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 状态信息卡片
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = when {
                            !isSystemMockEnabled -> MaterialTheme.colorScheme.tertiaryContainer
                            else -> MaterialTheme.colorScheme.primaryContainer
                        }
                    )
                ) {
                    Column(
                        modifier = Modifier.padding(12.dp)
                    ) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                when {
                                    !isSystemMockEnabled -> Icons.Default.Warning
                                    else -> Icons.Default.CheckCircle
                                },
                                contentDescription = null,
                                tint = when {
                                    !isSystemMockEnabled -> MaterialTheme.colorScheme.onTertiaryContainer
                                    else -> MaterialTheme.colorScheme.onPrimaryContainer
                                }
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = "系统状态",
                                fontWeight = FontWeight.Bold,
                                color = when {
                                    !isSystemMockEnabled -> MaterialTheme.colorScheme.onTertiaryContainer
                                    else -> MaterialTheme.colorScheme.onPrimaryContainer
                                }
                            )
                        }
                        Spacer(modifier = Modifier.height(4.dp))
                        Text(
                            text = systemMockStatus,
                            style = MaterialTheme.typography.bodySmall,
                            color = when {
                                !isSystemMockEnabled -> MaterialTheme.colorScheme.onTertiaryContainer
                                else -> MaterialTheme.colorScheme.onPrimaryContainer
                            }
                        )
                    }
                }
                
                if (!isSystemMockEnabled) {
                    Text(
                        text = "⚠️ 注意：要让其他应用获取到模拟位置，需要：\n" +
                                "1. 在开发者选项中启用'允许模拟位置'\n" +
                                "2. 选择本应用作为模拟位置应用",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                } else {
                    Text(
                        text = "✅ 系统级模拟已就绪，其他应用将获取到模拟位置",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.primary
                    )
                }
                
                Divider()
                
                Text(
                    text = "请输入要模拟的经纬度坐标：",
                    style = MaterialTheme.typography.bodyMedium
                )
                
                OutlinedTextField(
                    value = latitude,
                    onValueChange = { 
                        latitude = it
                        latitudeError = ""
                    },
                    label = { Text("纬度 (Latitude)") },
                    placeholder = { Text("例如: 39.9042") },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
                    isError = latitudeError.isNotEmpty(),
                    modifier = Modifier.fillMaxWidth(),
                    supportingText = if (latitudeError.isNotEmpty()) {
                        { Text(latitudeError, color = MaterialTheme.colorScheme.error) }
                    } else null
                )
                
                OutlinedTextField(
                    value = longitude,
                    onValueChange = { 
                        longitude = it
                        longitudeError = ""
                    },
                    label = { Text("经度 (Longitude)") },
                    placeholder = { Text("例如: 116.4074") },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
                    isError = longitudeError.isNotEmpty(),
                    modifier = Modifier.fillMaxWidth(),
                    supportingText = if (longitudeError.isNotEmpty()) {
                        { Text(longitudeError, color = MaterialTheme.colorScheme.error) }
                    } else null
                )
                
                OutlinedTextField(
                    value = accuracy,
                    onValueChange = { 
                        accuracy = it
                        accuracyError = ""
                    },
                    label = { Text("精度 (米)") },
                    placeholder = { Text("例如: 5.0") },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
                    isError = accuracyError.isNotEmpty(),
                    modifier = Modifier.fillMaxWidth(),
                    supportingText = if (accuracyError.isNotEmpty()) {
                        { Text(accuracyError, color = MaterialTheme.colorScheme.error) }
                    } else null
                )
                
                Text(
                    text = "提示：北京天安门坐标约为 39.9042, 116.4074",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        },
        confirmButton = {
            Button(
                onClick = {
                    if (validateInputs()) {
                        onSetSystemMock(
                            latitude.toDouble(), 
                            longitude.toDouble(), 
                            accuracy.toFloat()
                        )
                        onDismiss()
                    }
                },
                enabled = latitude.isNotEmpty() && longitude.isNotEmpty() && accuracy.isNotEmpty()
            ) {
                Icon(Icons.Default.PlayArrow, contentDescription = null)
                Spacer(modifier = Modifier.width(4.dp))
                Text("开始系统模拟")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}
